public class 下一个排列 {
    public void nextPermutation(int[] nums) {
        int n = nums.length;
        for (int i = n - 1;i >= 1;i--) {
            if (nums[i] > nums[i - 1]) {
                reverse(nums,i,n - 1);
                for (int j = i;j < n;j++) {
                    if (nums[j] > nums[i - 1]) {
                        swap(nums,j,i - 1);
                        return;
                    }
                }
            }
        }
        reverse(nums,0,n - 1);
    }

    public void reverse(int[] nums,int l,int r) {
        while (l < r) {
            swap(nums,l,r);
            l++;
            r--;
        }
    }
    public void swap(int[] nums,int l,int r) {
        int tmp = nums[l];
        nums[l] = nums[r];
        nums[r] = tmp;
    }
}
